<?php

/**
 * Twoir CMS系统 twCMS
 *
 * 商业版授权请访问axzz.cn查看。
 * 
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.05.01
*/

namespace App\Services\User;

use App\Models\User;
use Illuminate\Support\Facades\Auth as BaseAuth;
use Illuminate\Support\Facades\Hash;
use Session;

/**
 * 会员前端服务层
 */
class Auth extends UserService
{
    /**
     * 注册用户
     *
     * @param array $data
     * @param string $role
     * @return User
     */
    public function register(array $data, string $role = 'member'): User
    {
        $user = $this->create($data, $role);

        BaseAuth::login($user);

        return $user;
    }

    /**
     * 登陆
     * 
     * @param array $data
     * @return bool
     */
    public function login(array $data): bool
    {
        if (BaseAuth::attempt($data)) {
            // 登陆 + 1
            BaseAuth::user()->add()->first()->increment('login_count');

            return true;
        }

        return false;
    }

    /**
     * 是否登陆
     * 
     * @return bool
     */
    public function isLoggedIn(): bool
    {
        return BaseAuth::check();
    }

    /**
     * 更新密码
     * 
     * @param array $data
     * @return void
     */
    public function changePassword(array $data): void
    {
        BaseAuth::user()->password = Hash::make($data['new_password']);
        BaseAuth::user()->save();
    }

    /**
     * 检查当前密码是否正确
     * 
     * @param string $password
     * @return bool
     */
    public function checkCurrentPassword(string $password): bool
    {
        return Hash::check($password, BaseAuth::user()->password);
    }

    /**
     * 登出
     *
     * @return void
     */
    public function logout(): void
    {
        Session::flush();
        BaseAuth::logout();
    }
}